import { toRefs, ref } from "vue"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
import Query from "../../../zondy/lib/Query.js"
export const useHotMap = () => {
  const hideHotEle = ref(false)
  const heatmapsource = ref(null)
  const heatmaplayer = ref(null)
  const hotService = { name: "traffic", layerId: 2 }
  heatmapsource.value = new ol.source.Vector({ wrapX: false })
  heatmaplayer.value = new ol.layer.Heatmap({
    source: heatmapsource.value,
  })
  const value1 = ref(25)
  const value2 = ref(25)
  let hotmap = null
  function addHeatmap() {
    hideHotEle.value = true
    mapState.value.map.removeLayer(heatmaplayer.value)
    hotmap = new ol.Overlay({
      //要转换成overlay的HTML元素
      element: document.querySelector("#hotmap"),
      //当前窗口可见
      autoPan: true,
      //Popup放置的位置
      positioning: "bottom-center",
      //是否应该停止事件传播到地图窗口
      stopEvent: true,
      autoPanAnimation: {
        //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
        duration: 250,
      },
    })
    mapState.value.map.addOverlay(hotmap)
    const position = [114.25501441942471, 30.516860960342456]
    hotmap.setPosition(position)
    Query.queryByLayer({ service: hotService, success: hotsuccess })
    heatmaplayer.value.setBlur(parseInt(value2.value, 10))
    heatmaplayer.value.setRadius(parseInt(value1.value, 10))
    mapState.value.map.addLayer(heatmaplayer.value)
  }
  function hotsuccess(e) {
    var format = new Zondy.Format.PolygonJSON()
    //将MapGIS要素JSON反序列化为ol.Feature类型数组
    const features = format.read(e)
    heatmapsource.value.addFeatures(features)
  }
  function closeHotMap() {
    // heatmapsource.value.clear()
    // heatmaplayer.setVisible(false)
    mapState.value.map.removeLayer(heatmaplayer.value)
    hotmap.setPosition(undefined)
    hotmap = null
  }
  return { addHeatmap, closeHotMap, value1, value2, hideHotEle }
}
